/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bs.coregamelibrary.handler;

import com.bs.coregamelibrary.session.Session;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import java.io.IOException;

/**
 *
 * @author dungpt
 * @param <T>
 * @param <V>
 */
public abstract class CoreMessageHandler<T extends Object, V extends Session> extends SimpleChannelInboundHandler<T> {

    public static final AttributeKey<Session> SESSION = new AttributeKey<>("Session");

    private V getSessionFromChannel(ChannelHandlerContext ctx) {
        return (V) ctx.channel().attr(SESSION).get();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, T msg) throws Exception {

        V session = getSessionFromChannel(ctx);
        if (session != null) {
            processMessage(session, msg);
        } else {
            throw new Exception("dkm session null");
        }

    }

    protected abstract void processMessage(V session, T msg);

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (cause instanceof IOException) {
            ctx.close();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {

        System.out.println("New channel connected!");

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ctx.close();
    }

}
